import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import RehypeKatex from 'rehype-katex'
import RemarkMath from 'remark-math'
import RehypeHighlight from 'rehype-highlight'
import { CheckOutlined, CopyOutlined } from '@ant-design/icons'
import { Avatar, Button, message, Spin } from 'antd'
import { memo, useMemo, useRef, useState, type ReactElement } from 'react'
// import './ChatMessage.css'
import 'highlight.js/styles/github-dark.css'
import { CodeDrawer } from './CodeDrawer'

function PreCode(props: any) {
  const { children, useDrawer, spinning, ...rest } = props
  const preRef = useRef<HTMLPreElement | null>(null)
  const timerRef = useRef<any>(null)
  const reg = /language-(\w+)/
  const codeLanguage = reg.exec(children.props.className)?.[1]
  const [isCopyed, setIsCopyed] = useState(false)
  const handleClick = () => {
    if (timerRef.current) {
      return
    } else {
      const copyedCode = preRef.current!.querySelector('code')!.innerText
      navigator.clipboard.writeText(copyedCode as string)
      message.success('复制成功')
      setIsCopyed(true)
      timerRef.current = setTimeout(() => {
        setIsCopyed(false)
        timerRef.current = null
      }, 3000)
    }
  }

  if (useDrawer) {
    return (
      <Spin spinning={spinning}>
        <CodeDrawer
          content={
            <pre
              ref={preRef}
              {...rest}
              className="bg-[#e7e7e7] rounded-md border-2 border-gray-300 box-border p-[6px]"
            >
              {children}
            </pre>
          }
        />
      </Spin>
    )
  } else {
    return (
      <pre ref={preRef} {...rest} className="!bg-[#e7e7e7]">
        <div className="!font-[JetBrains_Mono] bg-gray-300 flex justify-between items-center rounded-t-md p-1.5">
          <div>{codeLanguage}</div>
          <div>
            {isCopyed ? (
              <Button onClick={handleClick} size="small" icon={<CheckOutlined />} />
            ) : (
              <Button onClick={handleClick} size="small" icon={<CopyOutlined />} />
            )}
          </div>
        </div>
        <div className="border-b-2 border-l-2 border-r-2 rounded-b-md border-gray-300">
          {children}
        </div>
      </pre>
    )
  }
}
function CustomCode(props: any) {
  const { children } = props
  return <code className="!font-[JetBrains_Mono]">{children}</code>
}

export const ChatMessage = memo(
  ({
    message,
    placement = 'right',
    avatar,
    loading = false,
  }: {
    message: string
    placement: 'left' | 'right'
    avatar?: ReactElement
    loading?: boolean
  }) => {
    const useDrawer = useMemo(() => {
      return (message.match(/\n/g) || []).length > 200
    }, [message])
    return (
      <div
        className={`w-full box-border flex gap-x-[12px] justify-start ${
          placement === 'right' ? 'flex-row-reverse' : 'flex-row'
        }`}
      >
        <Avatar className="flex-shrink-0" icon={avatar} />
        <div className="p-4 rounded-md bg-gray-200 box-border max-w-3xl">
          <ReactMarkdown
            remarkPlugins={[remarkGfm, RemarkMath]}
            // 使用RehypeHighlight插件来支持代码高亮
            rehypePlugins={[
              RehypeKatex,
              [
                RehypeHighlight,
                {
                  // 自动检测代码语言
                  detect: true,
                  // 忽略缺失的语言定义
                  ignoreMissing: true,
                },
              ],
            ]}
            components={{
              pre: (props) => <PreCode {...props} useDrawer={useDrawer} spinning={loading} />,
              code: CustomCode,
            }}
          >
            {message}
          </ReactMarkdown>
        </div>
      </div>
    )
  }
)
